<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>{{ hostname }}</title>
    {% load staticfiles %}
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">

    <link rel="stylesheet" href="{% static 'lib/layui/css/layui.css' %}">
    <link rel="stylesheet" href="{% static 'css/scroll-bar.css' %}">
    <link rel="stylesheet" href="{% static 'css/sub-page.css' %}">

    <link rel="stylesheet" href="//at.alicdn.com/t/font_693759_wytlyqhtdtj1nhfr.css">

    <link href="{% static 'webshell/static/img/favicon.png' %}" rel="icon" type="image/png">
    <link href="{% static 'webshell/static/css/bootstrap.min.css' %}" rel="stylesheet" type="text/css"/>
    <link href="{% static 'webshell/static/css/xterm.min.css' %}" rel="stylesheet" type="text/css"/>
    <link href="{% static 'webshell/static/css/fullscreen.min.css' %}" rel="stylesheet" type="text/css"/>


</head>
<body>
<div class="ok-body" id="meisbody">
    <!--form表单-->
    <table class="layui-hide" id="tableId" lay-filter="tableFilter"></table>
</div>
<div class="container" id="container">
                <a id="status" style="color: red;"></a>
    <div id="terminal"></div>
</div>
<!--js逻辑-->
<script src="{% static 'webshell/static/js/jquery.min.js' %}"></script>
<script src="{% static 'webshell/static/js/popper.min.js' %}"></script>
{#<script src="{% static 'webshell/static/js/bootstrap.min.js' %}"></script>#}
<script src="{% static 'webshell/static/js/xterm.min.js' %}"></script>
<script src="{% static 'webshell/static/js/fullscreen.min.js' %}"></script>
<script src="{% static 'lib/layui/layui.js' %}"></script>
<script>
    var jQuery;
    var wssh = {};
    jQuery(function ($) {
        var status = $('#status'),
            style = {},
            title_element = "webshell",
            DISCONNECTED = 0,
            CONNECTING = 1,
            CONNECTED = 2,
            state = DISCONNECTED,
            messages = {1: 'This client is connecting ...', 2: 'This client is already connnected.'};

        function parse_xterm_style() {
            var text = $('.xterm-helpers style').text();
            var arr = text.split('xterm-normal-char{width:');
            style.width = parseFloat(arr[1]);
            arr = text.split('div{height:');
            style.height = parseFloat(arr[1]);
        }


        function current_geometry() {
            if (!style.width || !style.height) {
                parse_xterm_style();
            }
            mebody=$('#meisbody');
            console.log(mebody.innerHeight());
            var cols = parseInt(window.innerWidth / style.width, 10) - 2;
            var rows = parseInt((window.innerHeight-mebody.innerHeight()) / style.height, 10);
            return {'cols': cols, 'rows': rows};
        }

        function format_geometry(cols, rows) {
            return JSON.stringify({'cols': cols, 'rows': rows});
        }


        function read_as_text_with_decoder(file, callback, decoder) {
            var reader = new window.FileReader();

            if (decoder === undefined) {
                decoder = new window.TextDecoder('utf-8', {'fatal': true});
            }

            reader.onload = function () {
                var text;
                try {
                    text = decoder.decode(reader.result);
                } catch (TypeError) {
                    console.log('Decoding error happened.');
                } finally {
                    if (callback) {
                        callback(text);
                    }
                }
            };

            reader.onerror = function (e) {
                console.error(e);
            };

            reader.readAsArrayBuffer(file);
        }


        function read_as_text_with_encoding(file, callback, encoding) {
            var reader = new window.FileReader();

            if (encoding === undefined) {
                encoding = 'utf-8';
            }

            reader.onload = function () {
                if (callback) {
                    callback(reader.result);
                }
            };

            reader.onerror = function (e) {
                console.error(e);
            };

            reader.readAsText(file, encoding);
        }


        function read_file_as_text(file, callback, decoder) {
            if (!window.TextDecoder) {
                read_as_text_with_encoding(file, callback, decoder);
            } else {
                read_as_text_with_decoder(file, callback, decoder);
            }
        }


        function reset_wssh() {
            var name;

            for (name in wssh) {
                if (wssh.hasOwnProperty(name) && name !== 'connect') {
                    delete wssh[name];
                }
            }
        }


        function log_status(text) {
            console.log(text);
        }


        function ajax_complete_callback(resp) {
            {#btn.prop('disabled', false);#}

            if (resp.status !== 200) {
                log_status(resp.status + ': ' + resp.statusText);
                status.text( resp.statusText);
                state = DISCONNECTED;
                return;
            }

            var msg = resp.responseJSON;
            if (!msg.id) {
                log_status(msg.status);
                status.text( msg.status);
                state = DISCONNECTED;
                return;
            }

            if (window.location.protocol == 'https:') {
                var ws_url = 'wss://';
            } else {
                var ws_url = 'ws://';
            }
            var endpoint = ws_url + window.location.host.split(':')[0],
                url = endpoint + ":{{ webssh.webssh_port }}/ws?id=" + msg.id,

                sock = new window.WebSocket(url),
                encoding = 'utf-8',
                decoder = window.TextDecoder ? new window.TextDecoder(encoding) : encoding,
                terminal = document.getElementById('#terminal'),
                term = new window.Terminal({
                    cursorBlink: true,
                });

            console.log(url);
            if (!msg.encoding) {
                console.log('Unable to detect the default encoding of your server');
                msg.encoding = encoding;
            } else {
                console.log('The deault encoding of your server is ' + msg.encoding);
            }

            function resize_terminal(term) {
                var geometry = current_geometry();
                term.on_resize(geometry.cols, geometry.rows);
            }

            function term_write(text) {
                if (term) {
                    term.write(text);
                    if (!term.resized) {
                        resize_terminal(term);
                        term.resized = true;
                    }
                }
            }

            function set_encoding(new_encoding) {
                // for console use
                if (!new_encoding) {
                    console.log('An encoding is required');
                    return;
                }

                if (!window.TextDecoder) {
                    decoder = new_encoding;
                    encoding = decoder;
                    console.log('Set encoding to ' + encoding);
                } else {
                    try {
                        decoder = new window.TextDecoder(new_encoding);
                        encoding = decoder.encoding;
                        console.log('Set encoding to ' + encoding);
                    } catch (RangeError) {
                        console.log('Unknown encoding ' + new_encoding);
                    }
                }
            }

            wssh.set_encoding = set_encoding;
            set_encoding(msg.encoding);


            wssh.geometry = function () {
                // for console use
                var geometry = current_geometry();
                console.log('Current window geometry: ' + JSON.stringify(geometry));
            };

            wssh.send = function (data) {
                // for console use
                if (!sock) {
                    console.log('Websocket was already closed');
                    return;
                }

                if (typeof data !== 'string') {
                    console.log('Only string is allowed');
                    return;
                }

                try {
                    JSON.parse(data);
                    sock.send(data);
                } catch (SyntaxError) {
                    data = data.trim() + '\r';
                    sock.send(JSON.stringify({'data': data}));
                }
            };

            wssh.reset_encoding = function () {
                // for console use
                if (encoding === msg.encoding) {
                    console.log('Already reset to ' + msg.encoding);
                } else {
                    set_encoding(msg.encoding);
                }
            };

            wssh.resize = function (cols, rows) {
                // for console use
                if (term === undefined) {
                    console.log('Terminal was already destroryed');
                    return;
                }

                var valid_args = false;

                if (cols > 0 && rows > 0) {
                    var geometry = current_geometry();
                    if (cols <= geometry.cols && rows <= geometry.rows) {
                        valid_args = true;
                    }
                }

                if (!valid_args) {
                    console.log('Unable to resize terminal to geometry: ' + format_geometry(cols, rows));
                } else {
                    term.on_resize(cols, rows);
                }
            };

            term.on_resize = function (cols, rows) {
                if (cols !== this.geometry[0] || rows !== this.geometry[1]) {
                    console.log('Resizing terminal to geometry: ' + format_geometry(cols, rows));
                    this.resize(cols, rows);
                    sock.send(JSON.stringify({'resize': [cols, rows]}));
                }
            };

            term.on('data', function (data) {
                // console.log(data);
                sock.send(JSON.stringify({'data': data}));
            });

            sock.onopen = function () {
                $('.container').hide();
                term.open(terminal, true);
                {#term.toggleFullscreen(true);#}

                state = CONNECTED;
                title_element.text = title_text;
            };

            sock.onmessage = function (msg) {
                read_file_as_text(msg.data, term_write, decoder);
            };

            sock.onerror = function (e) {
                console.error(e);
            };

            sock.onclose = function (e) {
                console.log(e);
                term.destroy();
                term = undefined;
                sock = undefined;
                reset_wssh();
                $('.container').show();
                status.text(e.reason);
                state = DISCONNECTED;
                title_text = 'WebSSH';
                title_element.text = title_text;
            };

            $(window).resize(function () {
                if (term) {
                    resize_terminal(term);
                }
            });
        }


        function connect_with_options(data) {
            // use data from the arguments
            console.log(data);

            $.ajax({
                url: window.location.protocol + "//" + window.location.host.split(':')[0] + ":{{ webssh.webssh_port }}/",
                type: 'post',
                data: JSON.stringify(data),
                complete: ajax_complete_callback,
                crossDomain: true,
                cache: false,
            });
            return 'success';
            {#return username + '@' + hostname + ':' + port;#}
        }


        function connect(shelldatas) {
            // for console use
            var result, opts;

            if (state !== DISCONNECTED) {
                console.log(messages[state]);
                return;
            }
            result = connect_with_options(shelldatas);

            if (result) {
                state = CONNECTING;
                title_text = result;
            }
        }

        wssh.connect = connect;


        layui.use(['element', 'form', 'jquery', 'laydate', 'table'], function () {
            var element = layui.element;
            var table = layui.table;
            var form = layui.form;
            var $ = layui.jquery;


            table.render({
                elem: '#tableId',
                url: "{% url 'api_webshell_get' %}" + "?assetsid={{ assetsid }}",
                limit: 10,
                page: false,
                cols: [[
                    {#{type: 'checkbox'},#}
                    {field: 'network_ip', title: '主机IP', width: 160, sort: true},
                    {field: 'hostname', title: '主机名', width: 280},
                    {field: 'assetgroup__groupname', title: '所属资产组', width: 200},
                    {field: 'addtime', title: '创建时间', width: 200,},
                    {field: 'uptime', title: '更新时间', width: 200,},
                    {title: '操作', width: 200, templet: '#operationTpl', align: 'center'},
                ]],
                done: function (res, curr, count) {
                    $("#countNum").text(count);
                }
            });
            table.on('tool(tableFilter)', function (obj) {
                var data = obj.data;
                var layEvent = obj.event;
                data.types="asset";
                if (layEvent === 'initenvs') {
                    if (state !== DISCONNECTED) {
                        console.log(messages[state]);
                        return;
                    }
                    layer.msg('执行中...');
                    connect(data);
                } else if (layEvent === 'background') {
                    layer.confirm("确定要放到后台吗？", {skin: 'layui-layer-lan', icon: 2, title: '提示', anim: 6}, function () {
                        alert("放到后台执行");
                        {#$.ajax({#}
                        {#    type: 'post',#}
                        {#    url: "{% url 'api_initbase_del' %}", // ajax请求路径#}
                        {#    data: {#}
                        {#        data: JSON.stringify(data),#}
                        {#        csrfmiddlewaretoken: "{{ csrf_token }}",#}
                        {#    },#}
                        {#    dataType: 'json',#}
                        {#    success: function (data) {#}
                        {#        if (data["status"] == 0) {#}
                        {#            layer.msg("删除成功！", {icon: 6, time: 1000, anim: 4}, function () {#}
                        {#                parent.layer.close(parent.layer.getFrameIndex(window.name));#}
                        {#                location.replace(location.href);#}
                        {#            });#}
                        {#        } else if (data == 'error') {#}
                        {#            layer.msg('删除失败');#}
                        {#        }#}
                        {#    }#}
                        {# });#}

                    });
                } else if (layEvent === 'suresuccess') {
                    alert("执行完成，退出连接")
                }
                console.log(data);
            });
        })
    })
</script>
<script type="text/html" id="operationTpl">
{#    <a href="javascript:;" title="任务完成，断开连接" lay-event="suresuccess"><i class="layui-icon">&#xe617;</i></a>#}
{#    <a href="javascript:;" title="后台运行" lay-event="background"><i class="layui-icon">&#xe643;</i></a>#}
    <a href="javascript:;" title="确定执行" lay-event="initenvs"><i class="layui-icon">&#xe63f;</i></a>
     <a href="javascript:location.replace(location.href);" title="刷新">
{#            <i class="layui-icon layui-icon-refresh"></i>#}
            <i class="layui-icon">&#xe9aa;</i>
        </a>
</script>

</body>
</html>